import React, { useState, useEffect } from 'react';
import { View, Text, Input } from '@tarojs/components';
import { Search, Filter, Plus } from '@nutui/icons-react-taro';
import { ConfigProvider, Tabs } from '@nutui/nutui-react-taro'
import Taro from '@tarojs/taro';
import { taskApi } from '../../services/taskApi';
import './index.scss';

const ManagePage = () => {
  const [searchText, setSearchText] = useState('');
  const [activeTab, setActiveTab] = useState('0');
  const [taskList, setTaskList] = useState([]);

  // 定义Tab标签
  const tabs = [
    { title: '全部', value: '0' },
    { title: '进行中', value: '1' },
    { title: '已完成', value: '2' }
  ];

  // Tab切换处理函数
  const handleTabChange = (value) => {
    setActiveTab(value);
  };

  // 获取任务列表的函数
  const fetchTaskList = async () => {
    const data = await taskApi.getTaskList();
    setTaskList(data);
  };

  useEffect(() => {
    fetchTaskList();

    // 添加事件监听，当任务创建成功后刷新列表
    Taro.eventCenter.on('taskCreated', () => {
      fetchTaskList();
    });

    // 添加页面显示时的刷新逻辑
    const onShowHandler = () => {
      fetchTaskList();
    };

    Taro.eventCenter.on('pageShow', onShowHandler);

    // 组件卸载时移除事件监听
    return () => {
      Taro.eventCenter.off('taskCreated');
      Taro.eventCenter.off('pageShow', onShowHandler);
    };
  }, []);

  // 接收页面显示事件
  useEffect(() => {
    Taro.getCurrentInstance().page.onShow = () => {
      Taro.eventCenter.trigger('pageShow');
    };
  }, []);

  // 根据搜索文本和选中的Tab过滤任务
  const filteredTaskData = taskList.filter(task => {
    // 搜索过滤
    const matchesSearch = !searchText ||
      task.basic_task_requirements.toLowerCase().includes(searchText.toLowerCase()) ||
      task.name.toLowerCase().includes(searchText.toLowerCase());

    // Tab过滤
    const matchesTab =
      activeTab === '0' || // 全部
      (activeTab === '1' && task.status === '进行中') || // 进行中
      (activeTab === '2' && task.status === '已完成'); // 已完成

    return matchesSearch && matchesTab;
  });

  // 按任务开始时间的年月进行分组
  const groupedTasks = filteredTaskData.reduce((acc, task) => {
    const startDate = new Date(task.start_time);
    const year = startDate.getFullYear();
    const month = startDate.getMonth() + 1; // 月份从0开始，所以要+1
    const section = `${year}年${month}月`;

    if (!acc[section]) {
      acc[section] = [];
    }
    acc[section].push(task);
    return acc;
  }, {});

  // 处理任务点击事件
  const handleTaskClick = (taskId) => {
    console.log('查看任务详情:', taskId);
  };

  // 处理搜索输入变化
  const handleSearchChange = (e) => {
    setSearchText(e.detail.value);
  };

  const handleFilterClick = () => {
    console.log('筛选任务');
  };

  const handleCreateClick = () => {
    Taro.navigateTo({
      url: '/package-manage/pages/task-create/index'
    });
  };

  return (
    <ConfigProvider>
      <View className='manage-page'>
        <View className="search-bar">
          <Search size="18" color="#9ca3af" />
          <Input
            type="text"
            placeholder="搜索任务..."
            value={searchText}
            onInput={handleSearchChange}
          />
        </View>

        <Tabs
          value={activeTab}
          onChange={handleTabChange}
          activeType="button"
        >
          {tabs.map((tab) => (
            <Tabs.TabPane key={tab.value} title={tab.title} value={tab.value} />
          ))}
        </Tabs>

        <View className="task-list-container">
          {Object.keys(groupedTasks).length === 0 ? (
            <View className="empty-result">
              <Text>没有找到匹配的任务</Text>
            </View>
          ) : (
            Object.keys(groupedTasks).map(section => (
              <View key={section} className="task-section">
                <Text className="section-title">{section}</Text>

                {groupedTasks[section].map(task => (
                  <View
                    key={task.task_id}
                    className="task-card"
                    onClick={() => handleTaskClick(task.task_id)}
                  >
                    <View className="task-header">
                      <View className="task-info">
                        <Text className="task-title">{task.basic_task_requirements}</Text>
                        <Text className="task-assigned-to">分配给: {task.name}</Text>
                      </View>
                      <View className={`status-tag ${task.status === '进行中' ? 'processing' : task.status === '已完成' ? 'completed' : ''}`}>
                        {task.status}
                      </View>
                    </View>
                    <View className="task-footer">
                      <Text className="task-progress">进度: {task.progress}%</Text>
                      <Text className="task-date">{task.start_time.split(' ')[0].slice(5)} - {task.end_time.split(' ')[0].slice(5)}</Text>
                    </View>
                  </View>
                ))}
              </View>
            ))
          )}
        </View>

        <View className="action-bar">
          <View className="action-button filter-button" onClick={handleFilterClick}>
            <Filter size="16" color="#4b5563" />
            <Text className="button-text">筛选</Text>
          </View>
          <View className="action-button create-button" onClick={handleCreateClick}>
            <Plus size="20" color="#ffffff" />
            <Text className="button-text">新建任务</Text>
          </View>
        </View>
      </View>
    </ConfigProvider>
  );
};

export default ManagePage;
